<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <el-input v-model="deptName" placeholder="请输入组织名称" clearable
                  size="small" prefix-icon="el-icon-search" @keyup.enter.native="handleSelectOrgCode"
        />
        <el-tree style="margin-top: 20px"
                 :data="deptOptions"
                 :filter-node-method="filterNode"
                 :expand-on-click-node="false"
                 ref="tree"
                 default-expand-all
                 @node-click="handleNodeClick"
        />
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
          <el-row>
            <el-form-item label="手机号" prop="account">
              <el-input
                v-model="queryParams.account"
                placeholder="请输入手机号"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item label="性别" prop="account">
              <el-select
                v-model="queryParams.gender"
                placeholder="性别"
                clearable
                size="small"
              >
                <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="昵称" prop="nickName">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入昵称"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!--  <el-form-item label="创建时间" prop="createTime">
                <el-date-picker clearable size="small" style="width: 200px"
                  v-model="queryParams.createTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择创建时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="修改时间" prop="modifyTime">
                <el-date-picker clearable size="small" style="width: 200px"
                  v-model="queryParams.modifyTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择修改时间">
                </el-date-picker>
              </el-form-item>-->
            <el-form-item>
              <el-cascader :options="regions" v-model="selectedRegions" @change="handleChangeRegion" clearable
                           filterable placeholder="区域"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                         v-hasPermi="['user:userInfo:query']"
              >搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>

            <el-form-item>
              <el-button
                type="warning"
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['user:userInfo:export']"
              >导出
              </el-button>
              <el-button type="primary" size="mini" v-hasPermi="['user:userInfo:map']">
                <router-link to="/userMap" target="_blank">地图展示</router-link>
              </el-button>
            </el-form-item>
          </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <!--<el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
            >删除</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['user:userInfo:export']"
              v-if="false"
            >导出
            </el-button>
          </el-col>
          <el-col :span="1.5" v-if="false">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="allPush"
            >全推
            </el-button>
          </el-col>

        </el-row>

        <el-table v-loading="loading" :data="userList" border @selection-change="handleSelectionChange" stripe
                  @sort-change="handleSort"
        >
          <!--      <el-table-column type="selection" width="55" align="center"/>-->
          <el-table-column v-if="false" label="主键" align="center" prop="id"/>
          <el-table-column v-if="false" label="sourceId" align="center" prop="sourceId"/>
          <el-table-column v-if="false" label="sourceType" align="center" prop="sourceType"/>

          <el-table-column label="手机号" align="center" prop="account" width="120"/>
          <el-table-column label="昵称" align="center" prop="nickName" width="120" :show-overflow-tooltip="true"/>
          <el-table-column label="性别" align="center" prop="gender" width="120">
            <template slot-scope="scope">
              <template v-if="!scope.row.gender">
                <el-tag type="info">未知</el-tag>
              </template>
              <template v-else-if="scope.row.gender==='0'">
                <el-tag>男</el-tag>
              </template>
              <template v-else-if="scope.row.gender==='1'">
                <el-tag type="danger">女</el-tag>
              </template>
              <template v-else>
                <el-tag type="info">未知</el-tag>
              </template>
            </template>
          </el-table-column>

          <el-table-column label="手机类型" align="center" prop="sourceType" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.sourceType===1">ios</span>
              <span v-else-if="scope.row.sourceType===2">Android</span>
              <span v-else>未知</span>
            </template>
          </el-table-column>
          <el-table-column label="位置详情" align="center" prop="position" min-width="100" :show-overflow-tooltip="true"
                           v-if="false"
          >
            <template slot-scope="scope">
              {{ scope.row.position === '' ? '未知' : scope.row.position }}
            </template>
          </el-table-column>

          <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable="custom">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="修改时间" align="center" prop="modifyTime" width="180" v-if="false">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.modifyTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="定位时间" align="center" prop="latestTime" width="160" sortable="custom" v-if="false">
            <template slot-scope="scope">
              <span>{{ scope.row.positionReportTime === null ? '未知' : scope.row.positionReportTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="组织名称" align="center" prop="deptName" width="180" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" min-width="180">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleDetailsView(scope.row)"
                v-hasPermi="['user:userInfo:detail']"
              >详情
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-data"
                @click="handleDeviceStatisticView(scope.row)"
                v-hasPermi="['user:userInfo:deviceStatistic']"
              >统计
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['user:userInfo:push']"
                :disabled="(scope.row.sourceType!==1 && scope.row.sourceType!==2)"
              >推送
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList1"
        />
      </el-col>
    </el-row>


    <!-- 全推 -->
    <el-dialog :title="title" :visible.sync="open2" width="500px" append-to-body>
      <el-form ref="form" :model="form2" :rules="rules" label-width="80px">
        <el-form-item label="推送标题">
          <el-input v-model="form2.title"></el-input>
        </el-form-item>

        <el-form-item label="推送内容">
          <el-input type="textarea" v-model="form2.pushMessage"></el-input>
        </el-form-item>
        <el-form-item label="消息类型" v-if="false">
          <el-input v-model="form2.pustType" readonly></el-input>
        </el-form-item>
        <el-form-item label="操作码" v-if="false">
          <el-input v-model="form2.messageCode" readonly></el-input>
        </el-form-item>
        <el-form-item label="推送时间" prop="resource">
          <el-radio-group aria-checked="true" v-model="resource">
            <el-radio label="0">现在</el-radio>

          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="allPushButton">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 单推 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form1" :rules="rules" label-width="80px">
        <el-form-item label="推送标题">
          <el-input v-model="form1.title"></el-input>
        </el-form-item>

        <el-form-item label="推送内容">
          <el-input type="textarea" v-model="form1.pushMessage"></el-input>
        </el-form-item>
        <el-form-item label="消息类型" v-if="false">
          <el-input v-model="form1.pushType" readonly></el-input>
        </el-form-item>
        <el-form-item label="操作码" v-if="false">
          <el-input v-model="form1.messageCode" readonly></el-input>
        </el-form-item>
        <el-form-item label="推送时间" prop="resource">
          <el-radio-group aria-checked="true" v-model="resource">
            <el-radio label="0">现在</el-radio>

          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户详情 -->
    <el-dialog :title="detailDialogTitle" :visible.sync="detailDialogOpen" width="1100px" append-to-body
               :before-close="closeDetailDialog"
    >
      <div slot="title">
        <el-row>
          <div style="float: left">
            <el-avatar :size="30" :src="selectedAppUser.imgUrl"/>
          </div>
          <div style="float: left;margin-top: 8px;margin-left: 10px;font-weight: bold">
            {{ selectedAppUser.account }} ({{ selectedAppUser.nickName }})
          </div>
          <div style="float: right;margin-top: 8px;margin-right: 100px;font-weight: bold">刷新倒计时: {{ freshTime }}</div>
        </el-row>
      </div>

      <el-card>
        <el-row>
          <el-col :span="8" style="margin-top: 10px">
            <span style="font-weight: bold">性别:&nbsp;</span>
            <template v-if="selectedAppUser.gender==='0'">
              <el-tag>男</el-tag>
            </template>
            <template v-else-if="selectedAppUser.gender==='1'">
              <el-tag type="danger">女</el-tag>
            </template>
            <template v-else>
              <el-tag type="info">未知</el-tag>
            </template>
          </el-col>

          <el-col :span="8" style="margin-top: 10px">
            <span style="font-weight: bold">手机类型:&nbsp;</span>
            <template v-if="selectedAppUser.sourceType===1">
              ios
            </template>
            <template v-else-if="selectedAppUser.sourceType===2">
              Android
            </template>
            <template v-else>
              未知
            </template>
          </el-col>

          <el-col :span="8" style="margin-top: 10px">
            <span style="font-weight: bold"
            >定位时间:&nbsp; </span>
            {{ selectedAppUser.positionReportTime === null ? '未知' : selectedAppUser.positionReportTime }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="margin-top: 10px">
            <span style="font-weight: bold">创建时间:&nbsp; </span> {{ selectedAppUser.createTime }}
          </el-col>
          <el-col :span="16" style="margin-top: 10px">
            <span style="font-weight: bold">位置:&nbsp;</span>
            {{ selectedAppUser.position === '' ? '未知' : selectedAppUser.position }}
          </el-col>
        </el-row>
      </el-card>
      <el-tabs type="border-card" @tab-click="clickTabPane" v-model="selectedTabPane" style="margin-top: 10px">
        <el-tab-pane v-for="item in detailsDialogHomeList" :label="item.homeName" :name="item.id">
          <!--  显示网关信息  -->
          <template v-if="detailsDialogGatewayList.length>0">
            <el-descriptions :column="4" :label-style="{'font-weight': 'bold'}">
              <el-descriptions-item label="网关名称">
                <el-popover trigger="hover" placement="top-start">
                  <img :src="detailsDialogGatewayList[0].imgUrl" alt="" style="width: 100px;height: 100px">
                  <span slot="reference">
                    {{ detailsDialogGatewayList[0].name }}
                  </span>
                </el-popover>
              </el-descriptions-item>
              <el-descriptions-item label="网关MAC">{{ detailsDialogGatewayList[0].zigbeeMac }}</el-descriptions-item>
              <el-descriptions-item label="自动入网">
                <template v-if="detailsDialogGatewayList[0].zdrwbz==='Y'">
                  <div class="myTagOpen">是</div>
                </template>
                <template v-else>
                  <div class="myTagClose">否</div>
                </template>
              </el-descriptions-item>
              <el-descriptions-item label="是否布防">
                <template v-if="detailsDialogGatewayList[0].defendStatus==='01'">
                  <div class="myTagOpen">是</div>
                </template>
                <template v-else>
                  <div class="myTagClose">否</div>
                </template>
              </el-descriptions-item>
              <el-descriptions-item label="软件版本">
                {{ strInsert(detailsDialogGatewayList[0].softwareVersionNumber, 1, '.') }}
              </el-descriptions-item>
              <el-descriptions-item label="硬件版本">
                {{ strInsert(detailsDialogGatewayList[0].hardwareVersionNumber, 1, '.') }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ detailsDialogGatewayList[0].createTime }}</el-descriptions-item>
              <el-descriptions-item label="上报时间">{{ detailsDialogGatewayList[0].switchTime }}</el-descriptions-item>
              <el-descriptions-item label="网关位置">{{ detailsDialogGatewayList[0].address }}</el-descriptions-item>
            </el-descriptions>
          </template>
          <template v-else>
            暂无网关
          </template>
          <el-divider/>
          <!--  场景和设备  -->
          <el-row :gutter="20">
            <el-col :span="7">
              <el-form label-width="68px" :inline="true" @submit.native.prevent>
                <el-form-item label="场景名称">
                  <el-input size="small" style="width: 100px" v-model="sceneDetailQueryParams.sceneName" clearable
                            @keyup.enter.native="getSceneListByHomeId"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="getSceneListByHomeId">搜索
                  </el-button>
                </el-form-item>
              </el-form>
              <el-row>
                <el-col :span="18">
                  <template v-if="detailsDialogSceneList.length>0">
                    <el-table :data="detailsDialogSceneList" height="350">
                      <el-table-column label="场景名称" prop="sceneName" min-width="80" :show-overflow-tooltip="true"
                      >
                        <template slot-scope="scope">
                          <el-popover trigger="hover" placement="bottom">
                            <div style="width: 300px">
                              <el-descriptions :column="1">
                                <el-descriptions-item label="场景名称">{{ scope.row.sceneName }}</el-descriptions-item>
                                <el-descriptions-item label="场景编号">{{ scope.row.code }}</el-descriptions-item>
                              </el-descriptions>
                            </div>
                            <span slot="reference">
                              {{ scope.row.sceneName }}
                            </span>
                          </el-popover>
                        </template>

                      </el-table-column>
                      <el-table-column label="编号" width="50" prop="code" v-if="false"/>
                      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="60">
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-caret-right"
                            @click="controlScene(scope.row)"
                            v-hasPermi="['user:userInfo:sceneControl']"
                          >执行
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-pagination
                      :total="sceneDetailTotal"
                      layout="total,prev,next,jumper"
                      :page-size="sceneDetailPageSize"
                      @current-change="handleSceneCurrentPageChange"
                    />
                  </template>
                  <template v-else>
                    暂无场景
                  </template>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="17">
              <el-form label-width="68px" :inline="true" @submit.native.prevent>
                <el-form-item label="设备名称">
                  <el-input v-model="deviceDetailQueryParams.deviceName" size="small" clearable
                            @keyup.enter.native="getDeviceListByHomeId"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="getDeviceListByHomeId">搜索
                  </el-button>
                </el-form-item>
              </el-form>
              <template v-if="detailsDialogDeviceList.length>0">
                <el-table :data="detailsDialogDeviceList" height="350" @sort-change="handleDeviceSort" border>
                  <el-table-column label="设备名称" prop="deviceName" :show-overflow-tooltip="true" width="140">
                    <template slot-scope="scope">
                      <el-popover trigger="hover" placement="bottom">
                        <div style="width: 300px">
                          <el-descriptions :column="1">
                            <el-descriptions-item label="设备类型">{{ scope.row.deviceType }}</el-descriptions-item>
                            <el-descriptions-item label="类型名称">{{ scope.row.defaultDeviceName }}</el-descriptions-item>
                            <el-descriptions-item label="设备MAC">{{ scope.row.deviceMac }}</el-descriptions-item>
                          </el-descriptions>
                        </div>
                        <span slot="reference">
                          {{ scope.row.deviceName }}
                        </span>
                      </el-popover>
                    </template>
                  </el-table-column>

                  <el-table-column label="在网状态" width="80" align="center">
                    <template slot-scope="scope">
                      <template v-if="scope.row.lwbz==='0'">
                        <template v-if="scope.row.onlineType!=='3'">
                          <template v-if="scope.row.diffTime > (scope.row.onlineTime * 60)">
                            <div class="myTagOffline">离线</div>
                          </template>
                          <template v-else>
                            <div class="myTagOnline">在线</div>
                          </template>
                        </template>
                      </template>
                      <template v-else>
                        <div class="myTagOffNet">离网</div>
                      </template>
                    </template>
                  </el-table-column>

                  <el-table-column label="设备状态" prop="actions" :show-overflow-tooltip="true" align="center">
                    <template slot-scope="scope">
                      <div v-html="fetchStatus(scope.row.actions,scope.row.deviceType)">
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="上报时间" prop="switchTime" :show-overflow-tooltip="true" sortable="custom"
                                   width="160"
                  />

                  <el-table-column prop="actions" :show-overflow-tooltip="true" v-if="false" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.actions }}
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  :total="deviceDetailTotal"
                  layout="total,prev,next,jumper"
                  :page-size="deviceDetailPageSize"
                  @current-change="handleCurrentPageChange"
                />
              </template>
              <template v-else>
                暂无设备
              </template>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!--    用户设备统计对话框-->
    <el-dialog :title="deviceStatisticDialogTitle" :visible.sync="deviceStatisticDialogOpen" width="1100px"
               append-to-body
    >
      <div slot="title">
        <el-row>
          <div>{{ this.selectUserAccount }}({{ this.selectUserNickname }})的设备统计 总数 {{ this.deviceTotalCount }}</div>
        </el-row>
      </div>
      <div>
        <template v-if="userDeviceChartData.count.length>0">
          <bar-chart :chart-data="userDeviceChartData" :height="statisticHeight"/>
        </template>
        <template v-else>
          <div style="margin-top: 20px">
            <center>
              暂无数据
            </center>
          </div>
        </template>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDeviceStatisticExport" type="warning" icon="el-icon-download">导 出</el-button>
        <el-button @click="deviceStatisticDialogOpen=false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { exportUser1, jpushToAllUser, jpushToOneUser, listAppUser } from '@/api/system/user'
import { CodeToText, provinceAndCityDataPlus } from 'element-china-area-data'
import { deptTreeSelect } from '@/api/system/dept'
import { getHomeListByAccountAndOrgCode } from '@/api/system/home'
import { getGatewayListByHomeId } from '@/api/system/gateway'
import { fetchStatus, getDeviceListByHomeId } from '@/api/system/device'
import { getSceneListByHomeId, triggerScene } from '@/api/system/scene'
import BarChart from '@/views/dashboard/BarChart'
import { exportUserDeviceChart, getUserDeviceChart } from '@/api/system/statistic'

export default {
  name: 'User1',
  components: {
    BarChart
  },
  data() {
    return {
      form1: {
        title: '',
        pushMessage: '',
        pushType: '070101',
        messageCode: '0',
        sourceId: '',
        id: '',
        sourceType: '',
        orgCode: undefined
      },
      form2: {
        title: '卓悦智能',
        pushMessage: ''
        // pushType: '070101',
        //messageCode: '0',
        // sourceId:'',
        // id:'',
        //sourceType:''
      },
      //radio:'0',
      resource: '0',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // APP用户表格数据
      userList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      open2: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        account: undefined,
        nickName: undefined,
        createTime: undefined,
        modifyTime: undefined,
        position: null,
        selectedOrgCode: null,
        orderByCreateTime: undefined,
        orderByLatestTime: undefined,
        deptId: undefined,
        gender: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyUserId: [
          { required: true, message: '所属公司账号ID不能为空', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '用户账号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      },
      // 中国省、市
      regions: provinceAndCityDataPlus,
      // 选择的区域
      selectedRegions: [],
      // 组织编码
      orgCodeOptions: [],
      // 部门树选项
      deptOptions: undefined,
      deptName: undefined,

      // 所选组织的名称
      selectedDeptName: undefined,

      // 详情对话框的标题
      detailDialogTitle: '',
      // 详情对话框是否显示
      detailDialogOpen: false,

      // 详情页的家庭列表
      detailsDialogHomeList: [],
      // 详情页的网关列表
      detailsDialogGatewayList: [],
      // 详情页的场景列表
      detailsDialogSceneList: [],
      // 详情页的设备列表
      detailsDialogDeviceList: [],
      // 设备分页数据
      deviceDetailPageNum: 1,
      deviceDetailPageSize: 20,
      deviceDetailTotal: 0,
      // 场景分页数据
      sceneDetailPageNum: 1,
      sceneDetailPageSize: 20,
      sceneDetailTotal: 0,
      // 当前选项卡选择的家庭ID
      selectedHomeId: null,
      // 设备查询参数
      deviceDetailQueryParams: {
        pageNum: 1,
        pageSize: 20,
        homeId: undefined,
        deviceName: undefined,
        orderBySwitchTime: undefined
      },
      // 场景查询参数
      sceneDetailQueryParams: {
        pageNum: 1,
        pageSize: 20,
        homeId: undefined,
        sceneName: undefined
      },
      // 选择的选项卡
      selectedTabPane: undefined,

      genderOptions: [{ value: '0', label: '男' }, { value: '1', label: '女' }, { value: '2', label: '未知' }],

      // 当前选择的用户信息
      selectedAppUser: {},

      // 该用户的系统名称
      selectDeptName: undefined,

      // 用户设备统计标题
      deviceStatisticDialogTitle: '',
      // 用户设备统计对话框显示状态
      deviceStatisticDialogOpen: false,

      // 报表数据
      userDeviceChartData: {
        yAxisData: [], count: [], position: 'right', color: '#2c5d3c'
      },

      // 报表的高度
      statisticHeight: '500px',

      // 报表的滑动条
      dataZoom: [{
        type: 'inside',
        start: 0,
        yAxisIndex: [0]
      },
        {
          type: 'slider',
          start: 0,
          yAxisIndex: [0]
        }],

      // 设备总数
      deviceTotalCount: 0,
      // 设备统计选中的用户手机号
      selectUserAccount: undefined,
      // 设备统计选中的用户昵称
      selectUserNickname: '',
      // 设备统计选中的用户组织编码
      selectUserOrgCode: undefined,

      // 详情页定时器
      timer: '',
      // 页面刷新定时器毫秒时间
      timeMillisecond: 5000,
      // 倒计时定时器
      timer2: '',
      // 刷新倒计时计数
      freshTime: 5
    }
  },
  watch: {
    deptName(val) {
      let orgCode = null
      if (this.deptOptions[0].label === val) {
        orgCode = this.deptOptions[0].orgCode
      } else {
        let deptNode = this.getNodeByDeptNameOfTree(this.deptOptions[0], val)
        if (deptNode) {
          orgCode = deptNode.orgCode
        }
      }
      this.queryParams.selectedOrgCode = orgCode
    }
  },
  created() {
    this.getList1()
    this.getTreeselect()
  },
  methods: {
    fetchStatus,
    /** 查询APP用户列表 */
    getList1() {
      this.loading = true

      if (!this.selectDeptName) {
        this.selectDeptName = this.$store.getters.deptName
      }

      listAppUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.open2 = false
      this.reset1()
      this.reset2()
    },

    // 推送表单重置
    reset1() {
      this.form1 = {
        title: this.selectDeptName,
        pushMessage: '',
        pushType: '070101',
        messageCode: '0',
        sourceId: '',
        id: '',
        sourceType: ''
      }
      this.resetForm('form1')
    },
// 推送表单重置
    reset2() {
      this.form2 = {
        title: '卓悦智能',
        pushMessage: '',
        pushType: '070101',
        messageCode: '0',
        sourceId: '',
        id: '',
        sourceType: ''
      }
      this.resetForm('form2')
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        companyUserId: undefined,
        account: undefined,
        password: undefined,
        nickName: undefined,
        imgUrl: undefined,
        token: undefined,
        openidQq: undefined,
        openidWeixin: undefined,
        sourceType: undefined,
        sourceId: undefined,
        createTime: undefined,
        modifyTime: undefined,
        imei: undefined,
        tsbz: undefined,
        organizationCode: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList1()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加APP用户'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form1.id = row.id
      this.form1.orgCode = row.organizationCode
      this.form1.title = this.selectedDeptName || this.selectDeptName
      this.form1.sourceId = row.sourceId
      this.form1.sourceType = row.sourceType
      this.open = true
      this.title = `${row.account}(${row.nickName}) 推送消息`
    },

    // 查询用户设备统计
    handleDeviceStatisticView(row) {
      this.deviceStatisticDialogTitle = row.account + '(' + row.nickName + ')' + '的设备统计  总数 ' + this.deviceTotalCount
      this.deviceStatisticDialogOpen = true

      this.selectUserAccount = row.account
      this.selectUserNickname = row.nickName
      this.selectUserOrgCode = row.organizationCode

      // 查询用户的设备数量
      getUserDeviceChart({ account: row.account, orgCode: row.organizationCode }).then(response => {
        if (response.code === 200) {
          let chartData = response.data
          let yAxisData = []
          let count = []
          if (chartData.length > 0) {
            for (let i = 0, len = chartData.length; i < len; i++) {
              yAxisData.push(chartData[i].axisData)
              count.push(chartData[i].count)
            }
          }

          this.userDeviceChartData.yAxisData = yAxisData
          this.userDeviceChartData.count = count
          this.dataZoom[0].start = count.length
          this.dataZoom[1].start = count.length
          this.userDeviceChartData.dataZoom = this.dataZoom

          // 计算总数
          this.deviceTotalCount = 0
          for (let i = 0, len = count.length; i < len; i++) {
            this.deviceTotalCount += count[i]
          }
        }
      })
    },

    // 导出用户设备统计
    handleDeviceStatisticExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportUserDeviceChart({ account: this.selectUserAccount, orgCode: this.selectUserOrgCode })
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    /** 修改按钮操作 */
    allPush(row) {
      this.open2 = true
      this.title = '全用户推送'

    },

    submitForm: function() {
      var pp = this
      if (this.form1.id !== undefined) {
        jpushToOneUser(this.form1).then(response => {
          pp.msgSuccess('推送成功')
          pp.open = false
          pp.reset1()
        }, function(err) {
          pp.msgError('推送失败')
          pp.open = false
          pp.reset1()
        })
      }

    },
    allPushButton: function() {
      var pp = this
      //if (this.form2.id != undefined) {
      jpushToAllUser(this.form2).then(response => {
        pp.msgSuccess('推送成功')
        pp.open2 = false
        pp.reset2()
      }, function(err) {
        pp.msgError('推送失败')
        pp.open2 = false
        pp.reset2()
      })
      // }

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除APP用户编号为"' + ids + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delUser1(ids)
      }).then(() => {
        this.getList1()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    /*    handleExport() {
           this.download('system/user1/export', {
           //this.download('AppUser.xlsx', {
            ...this.queryParams
          }, `user1_${new Date().getTime()}.xlsx`)
        }*/

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportUser1(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    /**
     * 选择区域
     * @param selectedRegion
     */
    handleChangeRegion(selectedRegion) {
      let province = CodeToText[selectedRegion[0]]
      let city = CodeToText[selectedRegion[1]]
      if (province) {
        if (province === '全部') {
          province = ''
        }
        if (city === '市辖区' || city === '全部' || city === undefined) {
          city = ''
        }
        this.queryParams.position = province + city
      } else {
        this.queryParams.position = null
      }

      this.getList1()
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.selectedDeptName = data.label
      this.deptName = data.label
      this.queryParams.selectedOrgCode = data.orgCode
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleSelectOrgCode() {
      this.$refs.tree.filter(this.deptName)
      this.handleQuery()
    },
    /**
     * 通过组织名称查询组织结构树中的对应节点
     * @param treeNode
     * @param deptName
     * @returns {*}
     */
    getNodeByDeptNameOfTree(treeNode, deptName) {
      let childrenNodes = treeNode.children
      if (childrenNodes) {
        for (let i = 0, len = childrenNodes.length; i < len; i++) {
          if (childrenNodes[i].label === deptName) {
            return childrenNodes[i]
          }
        }

        for (let i = 0, len = childrenNodes.length; i < len; i++) {
          this.getNodeByDeptNameOfTree(childrenNodes[i], deptName)
        }
      }
    },

    /**
     * 点击排序按钮
     * @param event
     */
    handleSort(event) {
      // 转换排序的字符串, 将其转为sql中的形式
      let orderType = null
      if (event.order) {
        orderType = event.order === 'ascending' ? 'asc' : 'desc'
      }

      //先清空之前的排序
      this.queryParams.orderByCreateTime = undefined
      this.queryParams.orderByLatestTime = undefined

      // 设置查询参数中相应的排序标识字段
      if (event.prop === 'createTime') {
        this.queryParams.orderByCreateTime = orderType
      }
      if (event.prop === 'latestTime') {
        this.queryParams.orderByLatestTime = orderType
      }

      this.getList1()
    },

    /**
     * 点击用户详情
     */
    handleDetailsView(appUserInfo) {
      this.selectedAppUser = { ...appUserInfo }
      // 查询该用户的所有自有家庭
      this.getHomeByAccountAndOrgCode(appUserInfo.account, appUserInfo.organizationCode)
      // this.detailDialogTitle = appUserInfo.account + '的详情'
      this.detailDialogOpen = true
    },

    /**
     * 查询详情页家庭列表
     * @param account
     * @param orgCode
     */
    getHomeByAccountAndOrgCode(account, orgCode) {
      getHomeListByAccountAndOrgCode({ account, orgCode }).then(response => {
        this.detailsDialogHomeList = response.rows

        // 查询第一个选项卡的数据
        if (this.detailsDialogHomeList.length > 0) {
          this.selectedTabPane = this.detailsDialogHomeList[0].id
          this.gateFirstTabData()
        }
      })
    },

    /**
     * 查询家庭下的网关列表
     * @param homeId
     */
    getGatewayListByHomeId() {
      getGatewayListByHomeId({ homeId: this.selectedHomeId }).then(response => {
        this.detailsDialogGatewayList = response.rows
      })
    },

    /**
     * 查询家庭下的设备列表
     */
    getDeviceListByHomeId() {
      getDeviceListByHomeId(this.deviceDetailQueryParams).then(response => {
        this.detailsDialogDeviceList = response.rows
        this.deviceDetailTotal = response.total
      })
    },

    /**
     * 查询家庭下的场景列表
     * @param homeId
     */
    getSceneListByHomeId() {
      getSceneListByHomeId(this.sceneDetailQueryParams).then(response => {
        this.detailsDialogSceneList = response.rows
        this.sceneDetailTotal = response.total
      })
    },

    /**
     * 重置设备查询参数
     */
    resetDeviceQuery() {
      this.deviceDetailQueryParams = {
        pageNum: 1,
        pageSize: 20,
        homeId: undefined,
        deviceName: undefined
      }
    },

    /**
     * 重置场景查询参数
     */
    resetSceneQuery() {
      this.sceneDetailQueryParams = {
        pageNum: 1,
        pageSize: 20,
        homeId: undefined,
        sceneName: undefined
      }
    },

    /**
     * 点击了选项卡
     * @param tab
     */
    clickTabPane(tab) {
      // 销毁定时器
      clearInterval(this.timer)
      clearInterval(this.timer2)

      this.resetDeviceQuery()
      this.resetSceneQuery()
      let homeId = tab.name
      this.selectedHomeId = homeId
      this.deviceDetailQueryParams.homeId = homeId
      this.sceneDetailQueryParams.homeId = homeId

      this.getGatewayListByHomeId()
      this.getSceneListByHomeId()
      this.getDeviceListByHomeId()

      // 重新设置定时器
      this.setDetailTimer()
      this.freshTime = this.timeMillisecond / 1000
      this.setFreshTimer()
    },

    /**
     * 获取第一个选项卡的数据
     */
    gateFirstTabData() {
      clearInterval(this.timer)
      clearInterval(this.timer2)

      this.resetDeviceQuery()
      this.resetSceneQuery()
      if (this.detailsDialogHomeList.length > 0) {
        let homeId = this.detailsDialogHomeList[0].id
        this.selectedHomeId = homeId
        this.deviceDetailQueryParams.homeId = homeId
        this.sceneDetailQueryParams.homeId = homeId

        this.getGatewayListByHomeId()
        this.getSceneListByHomeId()
        this.getDeviceListByHomeId()

        this.setDetailTimer()
        this.freshTime = this.timeMillisecond / 1000
        this.setFreshTimer()
      }
    },

    /**
     * 设备数据修改分页的页面, prev, next, jumper都会调用该函数
     * @param currentPage 跳转后的页码
     */
    handleCurrentPageChange(currentPage) {
      this.deviceDetailQueryParams.pageNum = currentPage
      this.getDeviceListByHomeId()
    },

    /**
     * 设备数据修改分页的页面, prev, next, jumper都会调用该函数
     * @param currentPage 跳转后的页码
     */
    handleSceneCurrentPageChange(currentPage) {
      this.sceneDetailQueryParams.pageNum = currentPage
      this.getSceneListByHomeId()
    },

    /**
     * 设备上报时间排序
     */
    handleDeviceSort(event) {
      // 转换排序的字符串, 将其转为sql中的形式
      let orderType = null
      if (event.order) {
        orderType = event.order === 'ascending' ? 'asc' : 'desc'
      }

      //先清空之前的排序
      this.deviceDetailQueryParams.orderBySwitchTime = undefined

      // 设置查询参数中相应的排序标识字段
      if (event.prop === 'switchTime') {
        this.deviceDetailQueryParams.orderBySwitchTime = orderType
      }

      this.getDeviceListByHomeId()
    },

    /**
     * 执行场景
     */
    controlScene(row) {
      this.$confirm('是否执行场景?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let sceneId = row.id
        triggerScene({ sceneId: sceneId }).then(response => {
          if (response.code === 200) {
            this.msgSuccess('执行成功')
          }
        })
      }).catch(function() {
      })
    },

    /**
     * 数字字符串每隔几位插入一个分隔符
     * @param str
     * @param length
     * @param separator
     * @returns {*}
     */
    strInsert(str, length, separator) {
      if (str == null) {
        return ''
      }
      let reg = new RegExp('\\d{1,' + length + '}', 'g')
      let ma = str.match(reg)
      return ma.join(separator)
    },

    /**
     * 单推对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /**
     * 设备详情对话框确认关闭
     */
    closeDetailDialog() {
      // 销毁定时器
      clearInterval(this.timer)
      clearInterval(this.timer2)
      this.detailDialogOpen = false
    },

    // 设置详情页定时器
    setDetailTimer() {
      this.timer = setInterval(() => {
        // 查询网关
        this.getGatewayListByHomeId()
        // 查询场景
        this.getSceneListByHomeId()
        // 查询设备
        this.getDeviceListByHomeId()
      }, this.timeMillisecond)
    },

    // 设置倒计时定时器
    setFreshTimer() {
      this.timer2 = setInterval(() => {
        if (this.freshTime === 1) {
          this.freshTime = this.timeMillisecond / 1000
        } else {
          this.freshTime--
        }
      }, 1000)
    }
  }
}
</script>
<style lang="scss" scoped>
.el-table::before {
  /*去掉表格最下面的横线*/
  height: 0;
}

/deep/ .myTagOffNet {
  border-radius: 5px;
  padding: 2px 4px;
  color: white;
  background-color: #FF3600;
  font-size: 10px;
  display: inline-block;
  *display: inline;
  *zoom: 1;
}

> > > .el-dialog__header {
}

> > > .el-dialog__body {
  padding-top: 0;
}
</style>
